package com.outsourcing.bottle.ui;

import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.BasicInfoEntry;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.domain.UserBasicInfo;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class SettingBasicActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private final int init_basic_info = 1;
	private final int error = 2;
	private final int result_code_residecity = 3;
	private final int result_code_birthcity = 4;
	private final int result_code_workcity = 5;
	private final int set_basic_info = 6;
	private final int result_code_career = 7;
	
	private Handler handler;
	private int mYear;
	private int mMonth;
	private int mDay;
	private BasicInfoEntry entry;
	private LoginUserInfoEntry userEntry;
	private String[] status;
	private String[] bloor = new String[] {"AB", "A", "B", "O"};
	private HashMap<String, String> paramsMap;
	
	private EditText nameView;
	private RelativeLayout resideLayout;
	private TextView resideView;
	private RelativeLayout birthcityLayout;
	private TextView birthcityView;
	private RelativeLayout workcityLayout;
	private TextView workcityView;
	private RelativeLayout birthdayLayout;
	private TextView birthdayView;
	private RelativeLayout careerLayout;
	private TextView careerView;
	private RelativeLayout statusLayout;
	private TextView statusView;
	private RelativeLayout bloorLayout;
	private TextView bloorView;
	private ImageView backView;
	private ImageView confirmView;
	private TextView loginAccountView;
	private TextView loginEmailView;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.setting_basic);
		handler = new Handler(this);
		initWidget();
		Calendar time = Calendar.getInstance();
        mYear = time.get(Calendar.YEAR);
		mMonth = time.get(Calendar.MONTH);
        mDay = time.get(Calendar.DAY_OF_MONTH);
        status = new String[] { getString(R.string.setting_basic_status_single), 
    			getString(R.string.setting_basic_status_nosingle) };
        paramsMap = new HashMap<String, String>();
        UICore.eventTask(this, this, init_basic_info, "init_basic_info", null);
	}
	
	private void initWidget() {
		LoginUserInfoTable table = new LoginUserInfoTable();
		userEntry = table.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		if (userEntry.getBasicinfo_fullfill() == 1) {
			((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.GONE);
		} else {
			((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.VISIBLE);
			((TextView)findViewById(R.id.tv_profile_tips)).setText(userEntry.getBasicinfo_tip());
		}
		RemoteImageView img_head = (RemoteImageView) findViewById(R.id.iv_author_photo);
		String avatar = table.getLoginUserInfo(AppContext.getInstance().getLogin_uid()).getAvatar();
		if (TextUtil.notEmpty(avatar)) {
			img_head.setDefaultImage(R.drawable.avatar_default_small);
			img_head.setImageUrl(avatar);
		}

		nameView = (EditText) findViewById(R.id.setting_basic_name);
		nameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					UICore.eventTask(SettingBasicActivity.this, SettingBasicActivity.this, set_basic_info, "set_basic_info", null);
				}
				return false;
			}
		});
		resideLayout = (RelativeLayout) findViewById(R.id.setting_basic_reside_layout);
		resideLayout.setOnClickListener(this);
		resideView = (TextView) findViewById(R.id.setting_basic_reside_value);
		birthcityLayout = (RelativeLayout) findViewById(R.id.setting_basic_birthcity_layout);
		birthcityLayout.setOnClickListener(this);
		birthcityView = (TextView) findViewById(R.id.setting_basic_birthcity_value);
		workcityLayout = (RelativeLayout) findViewById(R.id.setting_basic_workcity_layout);
		workcityLayout.setOnClickListener(this);
		workcityView = (TextView) findViewById(R.id.setting_basic_workcity_value);
		birthdayLayout = (RelativeLayout) findViewById(R.id.setting_basic_birthday_layout);
		birthdayLayout.setOnClickListener(this);
		birthdayView = (TextView) findViewById(R.id.setting_basic_birthday_value);
		careerLayout = (RelativeLayout) findViewById(R.id.setting_basic_career_layout);
		careerLayout.setOnClickListener(this);
		careerView = (TextView) findViewById(R.id.setting_basic_career_value);
		statusLayout = (RelativeLayout) findViewById(R.id.setting_basic_status_layout);
		statusLayout.setOnClickListener(this);
		statusView = (TextView) findViewById(R.id.setting_basic_status_value);
		bloorLayout = (RelativeLayout) findViewById(R.id.setting_basic_bloor_layout);
		bloorLayout.setOnClickListener(this);
		bloorView = (TextView) findViewById(R.id.setting_basic_bloor_value);
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		confirmView = (ImageView) findViewById(R.id.topbar_confirm);
		confirmView.setOnClickListener(this);
		loginAccountView = (TextView) findViewById(R.id.setting_basic_username_value);
		loginEmailView = (TextView) findViewById(R.id.setting_basic_email_value);
	}
	
	private Dialog createTimePickerDialog(){
		return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			 mYear = year;
             mMonth = monthOfYear + 1;
             mDay = dayOfMonth;
             paramsMap.put("birthyear", String.valueOf(mYear));
             paramsMap.put("birthmonth", String.valueOf(mMonth));
             paramsMap.put("birthday", String.valueOf(mDay));
             String date = mYear + "-" + (mMonth < 10 ? "0" : "") + mMonth + '-' + (mDay < 10 ? "0" : "") + mDay;
             updateToDisplay(date);
		}
	};
	
	//更新时间
	 private void updateToDisplay(String date) {
		 birthdayView.setText(date);
	 }
	 
	 private void updateUI() {
		 findViewById(R.id.setting_basic_layout).setVisibility(View.VISIBLE);
		 LoginUserInfoTable table = new LoginUserInfoTable();
		 userEntry = table.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
		 if (userEntry.getBasicinfo_fullfill() == 1) {
			 ((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.GONE);
		 } else {
			 ((LinearLayout) findViewById(R.id.setting_basic_tips_layout)).setVisibility(View.VISIBLE);
			 ((TextView) findViewById(R.id.tv_profile_tips)).setText(userEntry.getBasicinfo_tip());
		 }
		 
		 if (entry != null) {
			 if (TextUtil.notEmpty(entry.getNickname())) {
				 ((RelativeLayout) findViewById(R.id.setting_basic_name_layout)).setVisibility(View.GONE);
			 } else {
				 ((RelativeLayout) findViewById(R.id.setting_basic_name_layout)).setVisibility(View.VISIBLE);
			 }
			 if (AppContext.language == 1) {
				 resideView.setText(entry.getResidecountry()+" " + entry.getBirthprovince()+" " + entry.getResidecity());
				 birthcityView.setText(entry.getBirthcountry()+" " + entry.getBirthprovince()+" " + entry.getBirthcity());
				 workcityView.setText(entry.getWorkcountry()+" " + entry.getWorkprovince()+" " + entry.getWorkcity());
			 } else {
				 resideView.setText(entry.getResidecity()+" " + entry.getBirthprovince()+" " + entry.getResidecountry());
				 birthcityView.setText(entry.getBirthcity()+" " + entry.getBirthprovince()+" " + entry.getBirthcountry());
				 workcityView.setText(entry.getWorkcity()+" " + entry.getWorkprovince()+" " + entry.getWorkcountry());
			 }
			 careerView.setText(entry.getCareer_subclass());
			 if (entry.getMarry() == 1) {
				 statusView.setText(getString(R.string.setting_basic_status_single));
			 } else if (entry.getMarry() == 2) {
				 statusView.setText(getString(R.string.setting_basic_status_nosingle));
			 }
			 bloorView.setText(entry.getBlood());
			 birthdayView.setText(entry.getBirthyear() + "-"
					+ (entry.getBirthmonth() < 10 ? "0" : "") + entry.getBirthmonth() + '-'
					+ (entry.getBirthday() < 10 ? "0" : "") + entry.getBirthday());
			 loginAccountView.setText(entry.getLogin_user());
			 loginEmailView.setText(entry.getLogin_email());
		 }
	 }
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == confirmView) {
			UICore.eventTask(this, this, set_basic_info, "set_basic_info", null);
		} else if (v == birthdayLayout) {
			createTimePickerDialog().show();
		} else if (v == birthcityLayout) {
			Intent intent = new Intent(this, SearchCityActivity.class);
			intent.putExtra("resultCode", result_code_birthcity);
			intent.putExtra("title", getString(R.string.setting_select_birthcity));
			startActivityForResult(intent, result_code_birthcity);
		} else if (v == resideLayout) {
			Intent intent = new Intent(this, SearchCityActivity.class);
			intent.putExtra("resultCode", result_code_residecity);
			intent.putExtra("title", getString(R.string.setting_select_residecity));
			startActivityForResult(intent, result_code_residecity);
		} else if (v == workcityLayout) {
			Intent intent = new Intent(this, SearchCityActivity.class);
			intent.putExtra("resultCode", result_code_workcity);
			intent.putExtra("title", getString(R.string.setting_select_workcity));
			startActivityForResult(intent, result_code_workcity);
		} else if (v == statusLayout) {
			doStatusAction();
		} else if (v == bloorLayout) {
			doBloorAction();
		} else if (v == careerLayout) {
			Intent intent = new Intent(this, SelectCareerActivity.class);
			intent.putExtra("resultCode", result_code_career);
			startActivityForResult(intent, result_code_career);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case error:
			onToast((String) msg.obj);
			break;
		case init_basic_info:
			updateUI();
			break;
		case set_basic_info:
			UICore.eventTask(this, this, init_basic_info, "init_basic_info", null);
			onToast((String) msg.obj);
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_basic_info:
			initBasicInfo();
			break;
		case set_basic_info:
			setBasicInfo();
			break;
		default:
			break;
		}
	}
	
	private void initBasicInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_basic_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				UserBasicInfo info = gson.fromJson(result, UserBasicInfo.class);
				if (info.getResults().getAuthok() == 0) {
					Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
					handler.sendMessage(msg);
				} else {
					entry = info.getBasic_info();
					handler.sendEmptyMessage(init_basic_info);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setBasicInfo() {
		String url = UrlConfig.set_basic_info;
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		if (TextUtil.notEmpty(entry.getNickname())) {
			paramsMap.put("nickname", entry.getNickname());
		} else {
			paramsMap.put("nickname", nameView.getText().toString().trim());
		}
		if (!paramsMap.containsKey("residecountry")) {
			paramsMap.put("residecountry", entry.getResidecountry());
		}
		if (!paramsMap.containsKey("birthcountry")) {
			paramsMap.put("birthcountry", entry.getBirthcountry());
		}
		if (!paramsMap.containsKey("workcountry")) {
			paramsMap.put("workcountry", entry.getWorkcountry());
		}
		
		if (!paramsMap.containsKey("resideprovince")) {
			paramsMap.put("resideprovince", entry.getResideprovince());
		}
		if (!paramsMap.containsKey("birthprovince")) {
			paramsMap.put("birthprovince", entry.getBirthprovince());
		}
		if (!paramsMap.containsKey("workprovince")) {
			paramsMap.put("workprovince", entry.getWorkprovince());
		}
		
		if (!paramsMap.containsKey("residecity")) {
			paramsMap.put("residecity", entry.getResidecity());
		}
		if (!paramsMap.containsKey("birthcity")) {
			paramsMap.put("birthcity", entry.getBirthcity());
		}
		if (!paramsMap.containsKey("workcity")) {
			paramsMap.put("workcity", entry.getWorkcity());
		}
		
		if (!paramsMap.containsKey("birthyear")) {
			paramsMap.put("birthyear", String.valueOf(entry.getBirthyear()));
		}
		if (!paramsMap.containsKey("birthmonth")) {
			paramsMap.put("birthmonth", String.valueOf(entry.getBirthmonth()));
		}
		if (!paramsMap.containsKey("birthday")) {
			paramsMap.put("birthday", String.valueOf(entry.getBirthday()));
		}
		
		if (!paramsMap.containsKey("career_class")) {
			paramsMap.put("career_class", entry.getCareer_class());
		}
		if (!paramsMap.containsKey("career_subclass")) {
			paramsMap.put("career_subclass", entry.getCareer_subclass());
		}
		if (!paramsMap.containsKey("career_classid")) {
			paramsMap.put("career_classid", String.valueOf(entry.getCareer_classid()));
		}
		if (!paramsMap.containsKey("career_subclassid")) {
			paramsMap.put("career_subclassid", String.valueOf(entry.getCareer_subclassid()));
		}
		if (!paramsMap.containsKey("marry")) {
			paramsMap.put("marry", String.valueOf(entry.getMarry()));
		}
		if (!paramsMap.containsKey("blood")) {
			paramsMap.put("blood", entry.getBlood());
		}
		if (!paramsMap.containsKey("residecityid")) {
			paramsMap.put("residecityid", String.valueOf(entry.getResidecityid()));
		}
		if (!paramsMap.containsKey("birthcityid")) {
			paramsMap.put("birthcityid", String.valueOf(entry.getBirthcityid()));
		}
		if (!paramsMap.containsKey("workcityid")) {
			paramsMap.put("workcityid", String.valueOf(entry.getWorkcityid()));
		}
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		getLoginUserInfo();
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, set_basic_info, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			if (loginUserInfo.getResults().getAuthok() == 1) {
				LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
				if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
					loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				} else {
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null) {
			return;
		}
		if (resultCode != result_code_career) {
			String city = data.getStringExtra("city");
			String province = data.getStringExtra("province");
			String country = data.getStringExtra("country");
			int cityid = data.getIntExtra("cityid", 0);
			if (country != null) {
				if (resultCode == result_code_residecity) {
					paramsMap.put("residecountry", country);
				} else if (resultCode == result_code_birthcity) {
					paramsMap.put("birthcountry", country);
				} else {
					paramsMap.put("workcountry", country);
				}
			} 
			if (province != null) {
				if (resultCode == result_code_residecity) {
					paramsMap.put("resideprovince", province);
				} else if (resultCode == result_code_birthcity) {
					paramsMap.put("birthprovince", province);
				} else {
					paramsMap.put("workprovince", province);
				}
			} 
			if (city != null) {
				if (resultCode == result_code_residecity) {
					paramsMap.put("residecity", city);
					paramsMap.put("residecityid", String.valueOf(cityid));
				} else if (resultCode == result_code_birthcity) {
					paramsMap.put("birthcity", city);
					paramsMap.put("birthcityid", String.valueOf(cityid));
				} else {
					paramsMap.put("workcity", city);
					paramsMap.put("workcityid", String.valueOf(cityid));
				}
			}
			switch (resultCode) {
			case result_code_residecity:
				paramsMap.put("residecityid", String.valueOf(cityid));
				if (AppContext.language == 1) {
					resideView.setText(country + province + city);
				} else {
					resideView.setText(city + province + country);
				}
				break;
			case result_code_birthcity:
				paramsMap.put("birthcityid", String.valueOf(cityid));
				if (AppContext.language == 1) {
					birthcityView.setText(country + province + city);
				} else {
					birthcityView.setText(city + province + country);
				}
				break;
			case result_code_workcity:
				paramsMap.put("workcityid", String.valueOf(cityid));
				if (AppContext.language == 1) {
					workcityView.setText(country + province + city);
				} else {
					workcityView.setText(city + province + country);
				}
				break;
			}
		} else {
			String career_class = data.getStringExtra("career_class");
			String career_subclass = data.getStringExtra("career_subclass");
			int career_classid = data.getIntExtra("career_classid", 0);
			int career_subclassid = data.getIntExtra("career_subclassid", 0);
			paramsMap.put("career_class", career_class);
			paramsMap.put("career_subclass", career_subclass);
			paramsMap.put("career_classid", String.valueOf(career_classid));
			paramsMap.put("career_subclassid", String.valueOf(career_subclassid));
			careerView.setText(career_subclass);
		}
	}
	
	private void doStatusAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, status);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						paramsMap.put("marry", String.valueOf(which + 1));
						statusView.setText(status[which]);
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}
	
	private void doBloorAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, bloor);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						paramsMap.put("blood", bloor[which]);
						bloorView.setText(bloor[which]);
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}
}
